local CommonOHOH = _G.CommonOHOH;
local M = CommonOHOH.class.new(script, CommonOHOH.files.BaseComponent());
local InstanceManager = CommonOHOH.load.InstanceManager();
local CallBackManager = CommonOHOH.load.CallBackManager();

function M.new(self,...)
	return M(self,...);
end;


function M.ctor(self, parent)
	M.super.ctor(self, parent);

    self.AttCtrl=self.parent:GetPrivateComponent("AttCtrl")
    self.MonsterFloder=self.AttCtrl:FindMonsterFolder()

    self.AllMonster={}
    for _,v in pairs(self.MonsterFloder:GetChildren()) do
        self:CreateMonster(v)
    end

    CallBackManager:AddRbxConnect(self,self.MonsterFloder.ChildAdded, function(obj,child)
        self:CreateMonster(child)
	end);


    CallBackManager:AddRbxConnect(self,self.MonsterFloder.ChildRemoved, function(obj,child)
        self:RemoveMonster(child)
	end);

    -- self.MonsterFloder.ChildAdded:Connect(function(child)
    --     self:CreateMonster(child)
    -- end)

    -- self.MonsterFloder.ChildRemoved:Connect(function(child)
    --     self:RemoveMonster(child)
    -- end)

end;


function M.dtor(self)
    for k,v in pairs(self.AllMonster) do
        v:dtor()
    end
    self.AllMonster={}
    
	M.super.dtor(self);
end;

function M.RemoveMonster(self,inst)
    -- print("移除怪--->1")
    if  self.AllMonster[inst] then
        self.AllMonster[inst]:dtor()
    end
    self.AllMonster[inst]=nil
end


function M.CreateMonster(self,inst)
    -- print("创建怪--->1")
    local class=inst:GetAttribute("server_class")
    
    local s,d=pcall(function()
        return CommonOHOH.load[class]().new(inst,self.parent)
    end)

    if s then
        self.AllMonster[inst]=d
    end

end

function M.GetAllMonster(self)
    return  self.AllMonster 
end

function M.GetSortMonsterByDistance(self,character) 
    local npos=character:GetPosition()
    local SortList={}
    for _,m in pairs(self:GetAllMonster()) do
        if m and m:IsCanAttack(character) then
            local mPos=m:GetPosition()
           local d=(mPos -npos).Magnitude
           table.insert(SortList,{
             obj=m, --攻击目标
             dis=d,
             pos=mPos,--攻击位置
           })
        end
    end

    -- 按离玩家距离排序
    table.sort(SortList,function(a,b)
        return a.dis<b.dis
    end)

    return SortList
end

-- 寻找最近的怪物
function M.FindNearMonster(self,character,...) 

    local list=self:GetSortMonsterByDistance(character)
    if #list>0 then
        return list[1]
    end
end


return M